import router from '@/router';
import nprogress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

// acquire userstore token
import { useUserStoreWithOut } from '@/store/modules/user';
import getPageTitle from '@/utils/get-page-title';

const whiteList = ['/','/login', '/auth-redirect'] // no redirect whitelist

nprogress.configure({ showSpinner: false }) // NProgress Configuration

// 2.1 permission judge
// 2.11 check all router
function hasPermission(roles: string[], route: any) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}
// 2.12 登录态
// 2.121 未登录

// 2.122 登录成功:不可以访问login


// global pre routing guard
router.beforeEach(async(to: any, from: any, next: any) => {
    // 1.1
    /**
     * to: 将要访问哪个路由
     * form: 从哪个路由而来
     * next: 是一个函数，表示放行，有next()和next('/login')两种
     */
    nprogress.start();

     // set page title
    document.title = getPageTitle(to.meta.title);
    const userStore = useUserStoreWithOut();
    let token = userStore.token;
    let username = userStore.username;
    // debugger;
    if (token) {
        // 未登录
        if(to.path == '/login'){
            // if is logged in, redirect to the home page
            next({ path: '/'});
        }else{
            // determine whether the user has obtained his permission roles through getInfo
            if(username){
                next();
                // next({ ...to, replace: true })
            }else{
                // no userinfo
                try {
                    await userStore.userInfo();
                    next();
                } catch (error) {
                    userStore.loginOut();
                    if(to.path == '/'){
                      next({ path: '/login',query:{redirect: 'home'}});
                    }else{
                      next({ path: '/login',query:{redirect: to.path}});
                    }
                }  
                // next();   
            }

            // next('/login');
            
        }
    }else{
        // if(to.path == '/login'){
        //     next();
        // }else{
        //     next({ path: '/login',query:{redirect: to.path}});
        // }
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            if(to.path == '/'){
                next(`/login?redirect=/home`)
            }else{
                next(`/login?redirect=${to.path}`)
            }
            nprogress.done()
        }

    }

    // next();

})

// global after routing guard
router.afterEach((to:any, from:any) => {
    // finish progress bar
    nprogress.done()
  })
  